package cn.com.yx.ms.service.impl;


import cn.com.yx.ms.domain.dbmodel.*;
import cn.com.yx.ms.domain.live.*;
import cn.com.yx.ms.domain.mq.*;
import cn.com.yx.ms.domain.mq.downstream.*;
import cn.com.yx.ms.domain.mq.upstream.*;
import cn.com.yx.ms.domain.program.ProgramFileModel;
import cn.com.yx.ms.persistence.*;
import cn.com.yx.ms.service.*;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.configuration.MQSend;
import cn.yx.framework.configuration.MyWebSocket;
import cn.yx.framework.log.MyLogger;
import cn.yx.framework.util.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.util.StringUtil;
import freemarker.ext.beans.HashAdapter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.*;


/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class MqServiceImpl implements IMqService {

    private static final Logger logger = LoggerFactory.getLogger(BaseConstant.class);

    @Resource
    private ILogService iLogService;
    @Resource
    private IUserContextService iUserContextService;
    @Resource
    private BaseConstant.SignalRConfig signalRConfig;
    @Resource
    private MQSend mqSend;
    @Resource
    private MqConfigMapper mqConfigMapper;
    @Resource
    private GgMainMapper ggMainMapper;
    @Resource
    private JmProgramMapper jmProgramMapper;
    @Resource
    private JmProgramFileMapMapper jmProgramFileMapMapper;
    @Resource
    private DevEquStoreMapper devEquStoreMapper;
    @Resource
    private DevStatusMapper devStatusMapper;
    @Resource
    private DevChannelNoMapper devChannelNoMapper;
    @Resource
    private DevVersionRecordMapper devVersionRecordMapper;
    @Resource
    private DevVersionMapMapper devVersionMapMapper;
    @Resource
    private UpDevUpdateReplayProgressMapper upDevUpdateReplayProgressMapper;
    @Resource
    private StlDevSyncMapper stlDevSyncMapper;
    @Resource
    private IDevService iDevService;
    @Resource
    private IMqService iMqService;
    @Resource
    private IHardwareService iHardwareService;
    @Resource
    private IGgService iGgService;
    @Resource
    private IProgramService iProgramService;
    @Resource
    private IRepairService iRepairService;
    @Resource
    private ILiveService iLiveService;
    @Resource
    private DevImgMapper devImgMapper;
    @Resource
    private CmdRecordMapper cmdRecordMapper;
    @Resource
    private DevAlertInfoMapper devAlertInfoMapper;
    @Resource
    private DevParamsMapper devParamsMapper;

    // region << MQ配置 >>
    @Override
    public List<MqConfigQueueModel> GetMqConfigQueues() {
        return mqConfigMapper.GetMqConfigQueues();
    }

    @Override
    public MqConfig findOne(int command, String type) {
        return mqConfigMapper.findOne(String.valueOf(command), type);
    }

    // 保存socket会话用Map
    private static Map<String, CmdRecord> websocketMap = new HashMap<String, CmdRecord>();

    //时间比较用参数
    private static Long timeMillions = 0L;

//    private static final
    // endregion

    // region << 下行 >>

    @Override
    public void send1001(String onOrOff, List<MqGridSelectedDevModel> mqGridSelectedDevModels) {
        //声明需要推送的消息对象
        MessageBase<D_Message1001> message1001 = null;
        if (mqGridSelectedDevModels != null || mqGridSelectedDevModels.size() > 0) {
            for (MqGridSelectedDevModel dev : mqGridSelectedDevModels) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message1001 = new MessageBase<D_Message1001>();
                    message1001.setMsgid(UUID.randomUUID().toString());
                    message1001.setDeviceid(dev.getEquipmentno());
                    message1001.setCommand(MqCommandType.C1001.getIndex());
                    message1001.setType(MqType.response.getName());
                    message1001.setStatus("200");
                    message1001.setContent(new D_Message1001());
                    message1001.getContent().setDebug(onOrOff);

                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C1001, JSON.toJSONString(message1001));
                    // 添加进数据库中
                    String debugModel = "1";
                    if (onOrOff.equals("on")) {
                        debugModel = "0";
                    }
                    if (null != mqGridSelectedDevModels || mqGridSelectedDevModels.size() > 0) {
                        for (MqGridSelectedDevModel mq : mqGridSelectedDevModels) {
                            DevParams devParams1 = devParamsMapper.selectByPrimaryKey(mq.getGuid());
                            //判断是否已经存在对应的记录
                            if (null == devParams1) {
                                //不存在
                                DevParams devParams = new DevParams();
                                devParams.setDebugmodel(debugModel);
                                devParams.setEquipmentguid(mq.getGuid());
                                devParams.setEquipmentno(mq.getEquipmentno());
                                devParams.setCreatetime(new Date());
                                devParamsMapper.insert(devParams);
                            } else {
                                devParams1.setDebugmodel(debugModel);
                                devParams1.setUpdatetime(new Date());
                                devParamsMapper.updateByPrimaryKey(devParams1);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void send1004(MqPushPowerOnOffModel mqPushPowerOnOffModel) {
        //声明需要推送的消息对象
        MessageBase<D_Message1004> message1004 = null;
        if (mqPushPowerOnOffModel != null) {
            for (MqGridSelectedDevModel dev : mqPushPowerOnOffModel.getMqGridSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message1004 = new MessageBase<D_Message1004>();
                    message1004.setMsgid(UUID.randomUUID().toString());
                    message1004.setDeviceid(dev.getEquipmentno());
                    message1004.setCommand(MqCommandType.C1004.getIndex());
                    message1004.setType(MqType.response.getName());
                    message1004.setStatus("200");
                    message1004.setContent(new D_Message1004());

                    if (mqPushPowerOnOffModel.getMessage1004() != null) {
                        message1004.getContent().setPoweron(mqPushPowerOnOffModel.getMessage1004().getPoweron());
                        message1004.getContent().setPoweroff(mqPushPowerOnOffModel.getMessage1004().getPoweroff());
                        // 添加进数据库中
                        if (null != mqPushPowerOnOffModel.getMqGridSelectedDevModels() || mqPushPowerOnOffModel.getMqGridSelectedDevModels().size() > 0) {
                            List<MqGridSelectedDevModel> mqGridSelectedDevModels = mqPushPowerOnOffModel.getMqGridSelectedDevModels();
                            for (MqGridSelectedDevModel mq : mqGridSelectedDevModels) {
                                DevParams devParams1 = devParamsMapper.selectByPrimaryKey(mq.getGuid());
                                //判断是否已经存在对应的记录
                                if (null == devParams1) {
                                    //不存在
                                    DevParams devParams = new DevParams();
                                    devParams.setPoweron(mqPushPowerOnOffModel.getMessage1004().getPoweron());
                                    devParams.setPoweroff(mqPushPowerOnOffModel.getMessage1004().getPoweroff());
                                    devParams.setEquipmentguid(mq.getGuid());
                                    devParams.setEquipmentno(mq.getEquipmentno());
                                    devParams.setCreatetime(new Date());
                                    devParamsMapper.insert(devParams);
                                } else {
                                    devParams1.setPoweron(mqPushPowerOnOffModel.getMessage1004().getPoweron());
                                    devParams1.setPoweroff(mqPushPowerOnOffModel.getMessage1004().getPoweroff());
                                    devParams1.setUpdatetime(new Date());
                                    devParamsMapper.updateByPrimaryKey(devParams1);
                                }
                            }
                        }

                    }

                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C1004, JSON.toJSONString(message1004));

                }
            }
        }
    }

    @Override
    public void send1005(MqPushThresholdModel mqPushThresholdModel) {
        //声明需要推送的消息对象
        MessageBase<D_Message1005> message1005 = null;
        if (mqPushThresholdModel != null) {
            for (MqGridSelectedDevModel dev : mqPushThresholdModel.getMqGridSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message1005 = new MessageBase<D_Message1005>();
                    message1005.setMsgid(UUID.randomUUID().toString());
                    message1005.setDeviceid(dev.getEquipmentno());
                    message1005.setCommand(MqCommandType.C1005.getIndex());
                    message1005.setType(MqType.response.getName());
                    message1005.setStatus("200");
                    message1005.setContent(new D_Message1005());

                    if (mqPushThresholdModel.getMessage1005() != null) {
                        message1005.getContent().setTemperaturemax(mqPushThresholdModel.getMessage1005().getTemperaturemax());
                        message1005.getContent().setTemperaturemin(mqPushThresholdModel.getMessage1005().getTemperaturemin());
                        message1005.getContent().setHumiditymax(mqPushThresholdModel.getMessage1005().getHumiditymax());
                        message1005.getContent().setHumiditymin(mqPushThresholdModel.getMessage1005().getHumiditymin());
                        // 添加进数据库中
                        if (null != mqPushThresholdModel.getMqGridSelectedDevModels() || mqPushThresholdModel.getMqGridSelectedDevModels().size() > 0) {
                            List<MqGridSelectedDevModel> mqGridSelectedDevModels = mqPushThresholdModel.getMqGridSelectedDevModels();
                            for (MqGridSelectedDevModel mq : mqGridSelectedDevModels) {
                                DevParams devParams1 = devParamsMapper.selectByPrimaryKey(mq.getGuid());
                                //判断是否已经存在对应的记录
                                if (null == devParams1) {
                                    //不存在
                                    DevParams devParams = new DevParams();
                                    devParams.setTemperaturemax(mqPushThresholdModel.getMessage1005().getTemperaturemax());
                                    devParams.setTemperaturemin(mqPushThresholdModel.getMessage1005().getTemperaturemin());
                                    devParams.setHumiditymax(mqPushThresholdModel.getMessage1005().getHumiditymax());
                                    devParams.setHumiditymin(mqPushThresholdModel.getMessage1005().getHumiditymin());
                                    devParams.setEquipmentguid(mq.getGuid());
                                    devParams.setEquipmentno(mq.getEquipmentno());
                                    devParams.setCreatetime(new Date());
                                    devParamsMapper.insert(devParams);
                                } else {
                                    devParams1.setTemperaturemax(mqPushThresholdModel.getMessage1005().getTemperaturemax());
                                    devParams1.setTemperaturemin(mqPushThresholdModel.getMessage1005().getTemperaturemin());
                                    devParams1.setHumiditymax(mqPushThresholdModel.getMessage1005().getHumiditymax());
                                    devParams1.setHumiditymin(mqPushThresholdModel.getMessage1005().getHumiditymin());
                                    devParams1.setUpdatetime(new Date());
                                    devParamsMapper.updateByPrimaryKey(devParams1);
                                }
                            }
                        }


                    }

                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C1005, JSON.toJSONString(message1005));

                }
            }
        }
    }

    @Override
    public void send1009(MqPushLedScreenOnOrOffModel mqPushLedScreenOnOrOffModel) {
//声明需要推送的消息对象
        MessageBase<D_Message1009> message1009 = null;
        if (mqPushLedScreenOnOrOffModel != null) {
            for (MqGridSelectedDevModel dev : mqPushLedScreenOnOrOffModel.getMqGridSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message1009 = new MessageBase<D_Message1009>();
                    message1009.setMsgid(UUID.randomUUID().toString());
                    message1009.setDeviceid(dev.getEquipmentno());
                    message1009.setCommand(MqCommandType.C1009.getIndex());
                    message1009.setType(MqType.response.getName());
                    message1009.setStatus("200");
                    message1009.setContent(new D_Message1009());

                    if (mqPushLedScreenOnOrOffModel.getMessage1009() != null) {
                        message1009.getContent().setStatus(mqPushLedScreenOnOrOffModel.getMessage1009().isStatus());
                        message1009.getContent().setStart(mqPushLedScreenOnOrOffModel.getMessage1009().getStart());
                        message1009.getContent().setEnd(mqPushLedScreenOnOrOffModel.getMessage1009().getEnd());

                        // 添加进数据库中
                        if (null != mqPushLedScreenOnOrOffModel.getMqGridSelectedDevModels() || mqPushLedScreenOnOrOffModel.getMqGridSelectedDevModels().size() > 0) {
                            List<MqGridSelectedDevModel> mqGridSelectedDevModels = mqPushLedScreenOnOrOffModel.getMqGridSelectedDevModels();
                            for (MqGridSelectedDevModel mq : mqGridSelectedDevModels) {
                                DevParams devParams1 = devParamsMapper.selectByPrimaryKey(mq.getGuid());
                                //判断是否已经存在对应的记录
                                if (null == devParams1) {
                                    //不存在
                                    DevParams devParams = new DevParams();
                                    if (mqPushLedScreenOnOrOffModel.getMessage1009().isStatus())
                                        devParams.setLedscreenstatus("on");
                                    else
                                        devParams.setLedscreenstatus("off");
                                    devParams.setLedscreenstarttime(mqPushLedScreenOnOrOffModel.getMessage1009().getStart());
                                    devParams.setLedscreenendtime(mqPushLedScreenOnOrOffModel.getMessage1009().getEnd());
                                    devParams.setEquipmentguid(mq.getGuid());
                                    devParams.setEquipmentno(mq.getEquipmentno());
                                    devParams.setCreatetime(new Date());
                                    devParamsMapper.insert(devParams);
                                } else {
                                    if (mqPushLedScreenOnOrOffModel.getMessage1009().isStatus())
                                        devParams1.setLedscreenstatus("on");
                                    else
                                        devParams1.setLedscreenstatus("off");
                                    devParams1.setLedscreenstarttime(mqPushLedScreenOnOrOffModel.getMessage1009().getStart());
                                    devParams1.setLedscreenendtime(mqPushLedScreenOnOrOffModel.getMessage1009().getEnd());
                                    devParams1.setUpdatetime(new Date());
                                    devParamsMapper.updateByPrimaryKey(devParams1);
                                }
                            }
                        }


                    }

                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C1009, JSON.toJSONString(message1009));

                }
            }
        }
    }

    @Override
    public void send2002(MqPushNoticeModel mqPushNoticeModel) {
        //获取所有公告
        List<GgMain> ggMains = ggMainMapper.findAll();

        //声明需要推送的消息对象
        MessageBase<D_Message2002> message2002 = null;
        if (mqPushNoticeModel.getMqSelectedDevModels() != null && mqPushNoticeModel.getMqSelectedNoticeModels() != null) {
            for (MqSelectedDevModel dev : mqPushNoticeModel.getMqSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getDevsn())) {
                    message2002 = new MessageBase<>();
                    message2002.setMsgid(UUID.randomUUID().toString());
                    message2002.setDeviceid(dev.getDevsn());
                    message2002.setCommand(MqCommandType.C2002.getIndex());
                    message2002.setType(MqType.response.getName());
                    message2002.setStatus("200");
                    message2002.setContent(new D_Message2002());
                    message2002.getContent().setNotice(new ArrayList<D_Message2002_Notice>());
                    for (MqSelectedNoticeModel notice : mqPushNoticeModel.getMqSelectedNoticeModels()) {
                        D_Message2002_Notice d2002Notice = null;
                        for (GgMain ggMain : ggMains) {
                            if (ggMain.getGuid().equals(notice.getId())) {
                                d2002Notice = new D_Message2002_Notice();
                                d2002Notice.setText(ggMain.getContent());
                                message2002.getContent().getNotice().add(d2002Notice);
                                break;
                            }
                        }
                    }

                    //存库绑定设备与公告
                    iGgService.saveDevGgMap(mqPushNoticeModel);

                    //发送MQ
                    mqSend.sendMsg(dev.getDevsn(), MqCommandType.C2002, JSON.toJSONString(message2002));


                }
            }
        }
    }

    @Override
    public void send2003(MqPushProgramModel mqPushProgramModel) {
        //获取所有节目
        List<JmProgram> jmPrograms = jmProgramMapper.findAll();
        //获取所有节目文件关系
        List<ProgramFileModel> programFileModels = jmProgramFileMapMapper.findAll();
        //声明需要推送的消息对象
        MessageBase<D_Message2003> message2003 = null;
        if (mqPushProgramModel.getMqSelectedDevModels() != null && mqPushProgramModel.getMqSelectedProgramModels() != null) {
            for (MqSelectedDevModel dev : mqPushProgramModel.getMqSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getDevsn())) {
                    message2003 = new MessageBase<>();
                    message2003.setMsgid(UUID.randomUUID().toString());
                    message2003.setDeviceid(dev.getDevsn());
                    message2003.setCommand(MqCommandType.C2003.getIndex());
                    message2003.setType(MqType.response.getName());
                    message2003.setStatus("200");

                    D_Message2003 d2003 = new D_Message2003();
                    d2003.setProgramcount(mqPushProgramModel.getMqSelectedProgramModels().size());
                    d2003.setSendtime(DateUtil.date2String(new Date(), "yyyy-MM-dd hh:mm:ss"));
                    message2003.setContent(d2003);
                    message2003.getContent().setPrograms(new ArrayList<D_Message2003_Programs>());

                    int programOrderIndex = 0;
                    for (MqSelectedProgramModel program : mqPushProgramModel.getMqSelectedProgramModels()) {
                        D_Message2003_Programs d2003Program = null;
                        for (JmProgram jmProgram : jmPrograms) {
                            if (jmProgram.getGuid().equals(program.getId())) {
                                d2003Program = new D_Message2003_Programs();
                                d2003Program.setProgramid(jmProgram.getGuid());
                                if (jmProgram.getType().equals(1)) {
                                    d2003Program.setPlaystart(DateUtil.date2String(jmProgram.getPlaystart(), "yyyy-MM-dd hh:mm:ss"));
                                    d2003Program.setPlayend(DateUtil.date2String(jmProgram.getPlayend(), "yyyy-MM-dd hh:mm:ss"));
                                }
                                d2003Program.setTitle(jmProgram.getTitle());
                                d2003Program.setType(jmProgram.getType());
                                d2003Program.setOrderindex(programOrderIndex++);
                                d2003Program.setFilepaths(new ArrayList<D_Message2003_Programs_FilePath>());

                                //添加节目文件
                                for (ProgramFileModel pfm : programFileModels) {
                                    if (pfm.getProgramid().equals(d2003Program.getProgramid())) {
                                        D_Message2003_Programs_FilePath dM2003Pf = new D_Message2003_Programs_FilePath();
                                        dM2003Pf.setFileid(pfm.getFileid());
                                        dM2003Pf.setPath(pfm.getFilepath());
                                        dM2003Pf.setOrderindex(pfm.getOrderindex());
                                        d2003Program.getFilepaths().add(dM2003Pf);
                                    }
                                }
                                message2003.getContent().getPrograms().add(d2003Program);
                                break;
                            }
                        }
                    }

                    //存库绑定设备与公告
                    iProgramService.saveDevProgramMap(mqPushProgramModel);

                    //推送MQ
                    mqSend.sendMsg(dev.getDevsn(), MqCommandType.C2003, JSON.toJSONString(message2003));


                }
            }
        }
    }

    @Override
    public void send2012(MqPushLiveConfigModel mqPushLiveConfigModel) {

        MessageBase<D_Message2012> message2012 = null;
        if (mqPushLiveConfigModel != null && mqPushLiveConfigModel.getMqSelectedDevModels() != null) {
            for (MqSelectedDevModel dev : mqPushLiveConfigModel.getMqSelectedDevModels()) {

                if (mqPushLiveConfigModel.getLiveConfigMainSavedModel() != null) {

                    LiveConfigMainSavedModel liveConfigMainSavedModel = mqPushLiveConfigModel.getLiveConfigMainSavedModel();

                    message2012 = new MessageBase<>();
                    message2012.setMsgid(UUID.randomUUID().toString());
                    message2012.setDeviceid(dev.getDevsn());
                    message2012.setCommand(MqCommandType.C2012.getIndex());
                    message2012.setType(MqType.response.getName());
                    message2012.setStatus("200");

                    D_Message2012 d2012 = new D_Message2012();
                    d2012.setNoticecontent(liveConfigMainSavedModel.getNoticecontent());
                    d2012.setNoticespeed(liveConfigMainSavedModel.getNoticespeed());
                    d2012.setBusdataurl(liveConfigMainSavedModel.getBusdataurl());
                    d2012.setVoicecount(liveConfigMainSavedModel.getVoicecount());
                    d2012.setFlashcount(liveConfigMainSavedModel.getFlashcount());
//                    d2012.setSitename(liveConfigMainSavedModel.getSitename());
                    if(StringUtil.isNotEmpty(dev.getName())){
                        d2012.setSitename(dev.getName());
                    }
                    d2012.setIsdebug(liveConfigMainSavedModel.getIsdebug());

                    // 直播流配置赋值
                    List<D_Message2012_LiveMedia> liveMedias = new ArrayList<>();
                    if (liveConfigMainSavedModel.getLivemedias() != null) {
                        for (LiveConfigLiveMediaModel liveUI : liveConfigMainSavedModel.getLivemedias()) {
                            D_Message2012_LiveMedia d2012Live = new D_Message2012_LiveMedia();
                            d2012Live.setChannelno(liveUI.getChannelno());
                            d2012Live.setUrl(liveUI.getUrl());
                            d2012Live.setDefaultchannel(liveUI.isDefaultchannel());
                            liveMedias.add(d2012Live);
                        }
                    }
                    d2012.setLivemedias(liveMedias);

                    // 插播配置赋值
                    List<D_Message2012_IntercutMedia> intercutMedias = new ArrayList<>();
                    if (liveConfigMainSavedModel.getIntercutmedias() != null) {
                        for (LiveConfigIntercutMediaModel intercutUI : liveConfigMainSavedModel.getIntercutmedias()) {
                            D_Message2012_IntercutMedia d2012Intercut = new D_Message2012_IntercutMedia();
                            d2012Intercut.setUrl(intercutUI.getUrl());
                            d2012Intercut.setLocalpath(intercutUI.getLocalpath());
                            d2012Intercut.setStart(intercutUI.getStart());
                            d2012Intercut.setEnd(intercutUI.getEnd());
                            intercutMedias.add(d2012Intercut);
                        }
                    }
                    d2012.setIntercutmedias(intercutMedias);

                    // 轮播配置赋值
                    List<D_Message2012_CarouselMedia> carouseMedias = new ArrayList<>();
                    if (liveConfigMainSavedModel.getCarousemedias() != null) {
                        for (LiveConfigCarouselMediaModel carouselUI : liveConfigMainSavedModel.getCarousemedias()) {
                            D_Message2012_CarouselMedia d2012Carousel = new D_Message2012_CarouselMedia();
                            d2012Carousel.setType(carouselUI.getType());
                            d2012Carousel.setUrl(carouselUI.getUrl());
                            d2012Carousel.setLocalpath(carouselUI.getLocalpath());
                            d2012Carousel.setOrderindex(carouselUI.getOrderindex());
                            carouseMedias.add(d2012Carousel);
                        }
                    }
                    d2012.setCarouselmedias(carouseMedias);

                    message2012.setContent(d2012);

                }

                mqSend.sendMsg(dev.getDevsn(), MqCommandType.C2012, JSON.toJSONString(message2012));
            }
        }
    }

    @Override
    public void send4002(List<MqGridSelectedDevModel> mqGridSelectedDevModels) {
        //声明需要推送的消息对象
        MessageBase<D_Message4002> message4002 = null;
        if (mqGridSelectedDevModels != null) {
            for (MqGridSelectedDevModel dev : mqGridSelectedDevModels) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message4002 = new MessageBase<D_Message4002>();
                    message4002.setMsgid(UUID.randomUUID().toString());
                    message4002.setDeviceid(dev.getEquipmentno());
                    message4002.setCommand(MqCommandType.C4002.getIndex());
                    message4002.setType(MqType.response.getName());
                    message4002.setStatus("200");
                    message4002.setContent(new D_Message4002());
                    message4002.getContent().setRestart("yes");
                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C4002, JSON.toJSONString(message4002));


                }
            }
        }
    }

    @Override
    public void send4003(String time, List<MqGridSelectedDevModel> mqGridSelectedDevModels) {
        //声明需要推送的消息对象
        MessageBase<D_Message4003> message4003 = null;
        if (mqGridSelectedDevModels != null) {
            for (MqGridSelectedDevModel dev : mqGridSelectedDevModels) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message4003 = new MessageBase<D_Message4003>();
                    message4003.setMsgid(UUID.randomUUID().toString());
                    message4003.setDeviceid(dev.getEquipmentno());
                    message4003.setCommand(MqCommandType.C4003.getIndex());
                    message4003.setType(MqType.response.getName());
                    message4003.setStatus("200");
                    message4003.setContent(new D_Message4003());
                    String ctime = DateUtil.date2String(new Date(), "yyyy-MM-dd") + " " + time;
                    message4003.getContent().setDatetime(ctime);
                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C4003, JSON.toJSONString(message4003));

                }
            }
        }
    }

    @Override
    public void send4005(String tts, List<MqGridSelectedDevModel> mqGridSelectedDevModels) {
        //声明需要推送的消息对象
        MessageBase<D_Message4005> message4005 = null;
        if (mqGridSelectedDevModels != null) {
            for (MqGridSelectedDevModel dev : mqGridSelectedDevModels) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message4005 = new MessageBase<D_Message4005>();
                    message4005.setMsgid(UUID.randomUUID().toString());
                    message4005.setDeviceid(dev.getEquipmentno());
                    message4005.setCommand(MqCommandType.C4005.getIndex());
                    message4005.setType(MqType.response.getName());
                    message4005.setStatus("200");
                    message4005.setContent(new D_Message4005());
                    message4005.getContent().setTtstext(tts);
                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C4005, JSON.toJSONString(message4005));


                }
            }
        }
    }

    @Override
    public void send4009(List<MqGridSelectedDevModel> mqGridSelectedDevModels) {
        //声明需要推送的消息对象
        MessageBase<D_Message4009> message4009 = null;
        if (mqGridSelectedDevModels != null) {
            for (MqGridSelectedDevModel dev : mqGridSelectedDevModels) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    message4009 = new MessageBase<D_Message4009>();
                    message4009.setMsgid(UUID.randomUUID().toString());
                    message4009.setDeviceid(dev.getEquipmentno());
                    message4009.setCommand(MqCommandType.C4009.getIndex());
                    message4009.setType(MqType.response.getName());
                    message4009.setStatus("200");

                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C4009, JSON.toJSONString(message4009));


                }
            }
        }
    }

    @Override
    public void send40064db(MqPushRelayModel mqPushRelayModel) {
        if (mqPushRelayModel.getMqGridSelectedDevModels() != null && mqPushRelayModel.getMqSelectedRelayModels() != null) {
            for (MqGridSelectedDevModel dev : mqPushRelayModel.getMqGridSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    // 修改继电器名称
                    if (mqPushRelayModel.isIschangename()) {
                        devChannelNoMapper.deleteChannelByDevsn(dev.getEquipmentno());
                        for (MqSelectedRelayModel replay : mqPushRelayModel.getMqSelectedRelayModels()) {
                            DevChannelNo devChannelNo = new DevChannelNo();
                            devChannelNo.setGuid(UUID.randomUUID().toString());
                            devChannelNo.setDevSn(dev.getEquipmentno());
                            devChannelNo.setChannelname(replay.getChannelname());
                            devChannelNo.setChannelno(replay.getChannelno());
                            if (replay.getStart() != null)
                                devChannelNo.setStart(replay.getStart().replace(":", ""));
                            if (replay.getEnd() != null)
                                devChannelNo.setEnd(replay.getEnd().replace(":", ""));

                            devChannelNo.setStatus(replay.getStatus().equals("true") ? "on" : "off");
                            devChannelNoMapper.insert(devChannelNo);
                        }
                    } else {
                        List<DevChannelNo> channelNos = devChannelNoMapper.findByDevsn(dev.getEquipmentno());
                        if (channelNos == null || channelNos.size() < 8) {
                            for (int i = 1; i <= 8; i++) {
                                DevChannelNo devChannelNo = new DevChannelNo();
                                devChannelNo.setGuid(UUID.randomUUID().toString());
                                devChannelNo.setDevSn(dev.getEquipmentno());
                                devChannelNo.setChannelno(i + "");
                                devChannelNo.setStatus("off");
                                devChannelNoMapper.insert(devChannelNo);
                            }
                        }
                        for (MqSelectedRelayModel replay : mqPushRelayModel.getMqSelectedRelayModels()) {
                            if (null == replay.getStart()) {
                                replay.setStart("");
                            }
                            if (null == replay.getEnd()) {
                                replay.setEnd("");
                            }
                            devChannelNoMapper.updateChannelNo(dev.getEquipmentno(),
                                    replay.getChannelno(),
                                    replay.getStatus().equals("true") ? "on" : "off",
                                    replay.getStart().replace(":", ""),
                                    replay.getEnd().replace(":", "")
                            );
                        }
                    }
                }
            }
        }
    }

    @Override
    public void send4006(MqPushRelayModel mqPushRelayModel) {

        //声明需要推送的消息对象
        if (mqPushRelayModel.getMqGridSelectedDevModels() != null && mqPushRelayModel.getMqSelectedRelayModels() != null) {
            for (MqGridSelectedDevModel dev : mqPushRelayModel.getMqGridSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getEquipmentno())) {
                    // 推送
                    MessageBase<D_Message4006> message4006 = new MessageBase<>();
                    message4006.setMsgid(UUID.randomUUID().toString());
                    message4006.setDeviceid(dev.getEquipmentno());
                    message4006.setCommand(MqCommandType.C4006.getIndex());
                    message4006.setType(MqType.response.getName());
                    message4006.setStatus("200");
                    message4006.setContent(new D_Message4006());
                    message4006.getContent().setChannels(new ArrayList<D_Message4006_Channel>());

                    // 获取数据库当前设备最新继电器集合
                    List<DevChannelNo> channels = devChannelNoMapper.findByDevsn(dev.getEquipmentno());

                    //for (MqSelectedRelayModel replay : mqPushRelayModel.getMqSelectedRelayModels()) {
                    for (DevChannelNo devChannelNo : channels) {
                        D_Message4006_Channel d406Channel = new D_Message4006_Channel();
                        d406Channel.setChannelname(devChannelNo.getChannelname());
                        d406Channel.setChannelno(devChannelNo.getChannelno());
                        if (StringUtils.isNoneBlank(devChannelNo.getStart())) {
                            d406Channel.setStart(devChannelNo.getStart().replace(":", ""));
                        }
                        if (StringUtils.isNoneBlank(devChannelNo.getEnd())) {
                            d406Channel.setEnd(devChannelNo.getEnd().replace(":", ""));
                        }
                        d406Channel.setStatus(devChannelNo.getStatus());
                        message4006.getContent().getChannels().add(d406Channel);
                    }
                    mqSend.sendMsg(dev.getEquipmentno(), MqCommandType.C4006, JSON.toJSONString(message4006));


                }
            }
        }
    }


    @Override
    public void send4007(MqPushUpdatePackageModel mqPushUpdatePackageModel) {


        List<DevVersionRecord> devVersionRecords = devVersionRecordMapper.findAllDevVersionRecord();

        //声明需要推送的消息对象
        MessageBase<D_Message4007> message4007 = null;
        if (StringUtils.isNoneBlank(mqPushUpdatePackageModel.getVersion()) && mqPushUpdatePackageModel.getMqSelectedDevModels() != null) {
            for (MqSelectedDevModel dev : mqPushUpdatePackageModel.getMqSelectedDevModels()) {
                if (StringUtils.isNoneBlank(dev.getDevsn())) {
                    message4007 = new MessageBase<>();
                    message4007.setMsgid(UUID.randomUUID().toString());
                    message4007.setDeviceid(dev.getDevsn());
                    message4007.setCommand(MqCommandType.C4007.getIndex());
                    message4007.setType(MqType.response.getName());
                    message4007.setStatus("200");
                    message4007.setContent(new D_Message4007());
                    message4007.getContent().setVersion(mqPushUpdatePackageModel.getVersion());

                    DevVersionRecord currentVersionRecord = null;
                    for (DevVersionRecord devVersionRecord : devVersionRecords) {
                        if (mqPushUpdatePackageModel.getVersion().equals(devVersionRecord.getVersion())) {
                            currentVersionRecord = devVersionRecord;
                            message4007.getContent().setPath("/apk/" + devVersionRecord.getApkpath());
                            break;
                        }

                    }
                    mqSend.sendMsg4Up(dev.getDevsn(), MqCommandType.C4007, JSON.toJSONString(message4007));

                    if (currentVersionRecord != null) {
                        devVersionMapMapper.deleteByDevsn(dev.getDevsn());

                        DevVersionMap devVersionMap = new DevVersionMap();
                        devVersionMap.setGuid(UUID.randomUUID().toString());
                        devVersionMap.setDevsn(dev.getDevsn());
                        devVersionMap.setVersionid(currentVersionRecord.getGuid());
                        devVersionMap.setCreatetime(new Date());
                        if (mqPushUpdatePackageModel.isChecked()) {
                            devVersionMap.setIsupdatefromserver("1");
                        } else {
                            devVersionMap.setIsupdatefromserver("0");
                        }

                        devVersionMapMapper.insert(devVersionMap);
                    }

                    //删除设备和版本记录
                    upDevUpdateReplayProgressMapper.deleteByVersionAndDevsn(dev.getDevsn(), message4007.getContent().getVersion());
                    //删除更新记录
                    UpDevUpdateReplayProgress updateReplayProgress = new UpDevUpdateReplayProgress();
                    updateReplayProgress.setGuid(UUID.randomUUID().toString());
                    updateReplayProgress.setDevsn(dev.getDevsn());
                    updateReplayProgress.setVersion(message4007.getContent().getVersion());
                    updateReplayProgress.setPushtime(new Date());
                    updateReplayProgress.setPushpath(message4007.getContent().getPath());
                    updateReplayProgress.setRequesttype(mqPushUpdatePackageModel.getRequesttype());
                    upDevUpdateReplayProgressMapper.insert(updateReplayProgress);


                }
            }
        }
    }

    @Override
    public void send4010(List<MqSelectedDevModel> mqSelectedDevModelList) {

    }

    // endregion

    // region << 上行 >>

    @Override
    public void receive(String content) {
        try {


            //解析content
            JSONObject jsonObject = JSON.parseObject(content);
            String command = jsonObject.get("command").toString();
            String devsn = jsonObject.get("deviceid").toString();
            String styleid = ""; // 式样ID
            int length = content.getBytes("UTF-8").length;

            MqCommandType mqCommandType = MqCommandType.valueOf("C" + command);

            // webSocketMapInfo(mqCommandType.getIndex(), mqCommandType.getName(), devsn, length);

            MyLogger.log("/command/rest-上行/" + devsn + "/"
                            + mqCommandType.getIndex() + "-" + mqCommandType.getName() + "/",
                    content);


            switch (mqCommandType) {
                case C1009: //LED开关控制
                    iMqService.receive1009(devsn, content);
                    break;
                case C2002: //公告主请
                    iMqService.receive2002(devsn, content);
                    break;
                case C2003: //视频主请
                    iMqService.receive2003(devsn, content);
                    break;
                case C2012: //直播配置主请
                    iMqService.receive2012(devsn, content);
                    break;
                case C3001: //设备状态
                    PushWebPageSocket(content);
                    iMqService.receive3001(devsn, content);
                    break;
                case C3002: // 设备告警
                    PushWebPageSocket(content);
                    iMqService.receive3002(devsn, content);
                    break;
                case C3003: //心跳
                    PushWebPageSocket(content);
                    iMqService.receive3003(devsn, content);
                    break;
                case C4003:
                    iMqService.receive4003(devsn, content);
                    break;
                case C4007: //远程升级主请
                    iMqService.receive4007(devsn, content);
                    break;
                case C4008: //远程升级应答
                    iMqService.receive4008(devsn, content);
                    break;
                case C4009: //设备截屏
                    iMqService.receive4009(devsn, content);
                    break;
                case C2100:
                    iMqService.receive2100(devsn, content);
                    break;
                case C2101:
                    PushWebPageSocket(content);
                    iMqService.receive2101(devsn, content);
                    break;
                case C2010: // 多媒体资源主请
                case C2011: // 新公告主请
                case C5011: // 静态线路主请
                    styleid = jsonObject.get("styleid").toString();
                    int sendWsType = -1;
                    if (mqCommandType == MqCommandType.C2010) {
                        sendWsType = 0;
                    } else if (mqCommandType == MqCommandType.C2011) {
                        sendWsType = 1;
                    } else {
                        sendWsType = 2;
                    }
                    iDevService.syncDevTemplate(devsn,
                            styleid,
                            true,
                            sendWsType);
                    break;
            }

            //推送signalR
            //PushSignalR(content);


        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("----------------------------------------" + ex.getMessage());
        }


    }

    @Override
    public void receive1009(String devsn, String json) {
        MessageBase<U_Message1009> m1009 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message1009>>() {
        });

        // 获取当前设备关联的升级包
        D_Message1009 message1009 = new D_Message1009();
        DevParams devParams = devParamsMapper.selectByEquipmentno(m1009.getDeviceid());
        if (devParams != null) {
            message1009.setStatus(devParams.getLedscreenstatus().equals("on"));
            message1009.setStart(devParams.getLedscreenstarttime());
            message1009.setEnd(devParams.getLedscreenendtime());
        } else {
            DevEquStore devEquStore = devEquStoreMapper.selectByDevSn(devsn);
            devParams = new DevParams();
            devParams.setEquipmentguid(devEquStore.getEquipmentguid());
            devParams.setEquipmentno(devsn);
        }


        MqPushLedScreenOnOrOffModel mqPushLedScreenOnOrOffModel = new MqPushLedScreenOnOrOffModel();
        // 发送时控对象赋值
        mqPushLedScreenOnOrOffModel.setMessage1009(message1009);
        // 发送设备赋值
        List<MqGridSelectedDevModel> mqGridSelectedDevModels = new ArrayList<>();
        MqGridSelectedDevModel dev = new MqGridSelectedDevModel();
        dev.setGuid(devParams.getEquipmentguid());
        dev.setEquipmentno(devsn);
        mqGridSelectedDevModels.add(dev);
        mqPushLedScreenOnOrOffModel.setMqGridSelectedDevModels(mqGridSelectedDevModels);
        send1009(mqPushLedScreenOnOrOffModel);
    }

    @Override
    public void receive2002(String devsn, String json) {
        MqPushNoticeModel mqPushNoticeModel = new MqPushNoticeModel();

        //构造发送的设备
        List<MqSelectedDevModel> devs = new ArrayList<>();
        MqSelectedDevModel dev = new MqSelectedDevModel();
        dev.setDevsn(devsn);
        devs.add(dev);
        mqPushNoticeModel.setMqSelectedDevModels(devs);

        //构造设备关联公告
        List<MqSelectedNoticeModel> notices = new ArrayList<>();
        List<GgMain> ggMains = ggMainMapper.findByDevsn(devsn);
        if (ggMains != null && ggMains.size() > 0) {
            for (GgMain ggMain : ggMains) {
                MqSelectedNoticeModel notice = new MqSelectedNoticeModel();
                notice.setId(ggMain.getGuid());
                notice.setText(ggMain.getContent());
                notices.add(notice);
            }
        }
        mqPushNoticeModel.setMqSelectedNoticeModels(notices);


        send2002(mqPushNoticeModel);

    }

    @Override
    public void receive2003(String devsn, String json) {
        MqPushProgramModel mqPushProgramModel = new MqPushProgramModel();

        //构造发送的设备
        List<MqSelectedDevModel> devs = new ArrayList<>();
        MqSelectedDevModel dev = new MqSelectedDevModel();
        dev.setDevsn(devsn);
        devs.add(dev);
        mqPushProgramModel.setMqSelectedDevModels(devs);

        //构造设备关联节目数
        List<MqSelectedProgramModel> selectedProgramModels = new ArrayList<>();
        List<JmProgram> jmPrograms = jmProgramMapper.findByDevsn(devsn);
        if (jmPrograms != null && jmPrograms.size() > 0) {
            for (JmProgram jmProgram : jmPrograms) {
                MqSelectedProgramModel program = new MqSelectedProgramModel();
                program.setId(jmProgram.getGuid());
                program.setText(jmProgram.getTitle());
                selectedProgramModels.add(program);
            }
        }
        mqPushProgramModel.setMqSelectedProgramModels(selectedProgramModels);

        send2003(mqPushProgramModel);

    }

    @Override
    public void receive2012(String devsn, String json) {
        MqPushLiveConfigModel mqPushLiveConfigModel = new MqPushLiveConfigModel();

        if (StringUtils.isNoneBlank(devsn)) {
            LiveConfigMainSavedModel liveConfigMainSavedModel = iLiveService.findLiveConfigMainModelByEquipmentNo(devsn);
            mqPushLiveConfigModel.setLiveConfigMainSavedModel(liveConfigMainSavedModel);

            List<MqSelectedDevModel> devs = new ArrayList<>();
            MqSelectedDevModel dev = new MqSelectedDevModel();
            dev.setDevsn(devsn);
            devs.add(dev);
            mqPushLiveConfigModel.setMqSelectedDevModels(devs);

        }

        send2012(mqPushLiveConfigModel);
    }

    @Override
    public void receive2100(String devsn, String json) throws Exception {
        MessageBase<U_Message2100> m2100 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message2100>>() {
        });

        if (m2100 != null) {
            //if (StringUtils.isNoneBlank(m2100.getDeviceid()) && StringUtils.isNoneBlank(m2100.getStyleid())) {
            if (StringUtils.isNoneBlank(m2100.getDeviceid())) {
                iDevService.syncDevTemplate(m2100.getDeviceid(), m2100.getStyleid(), "1");
            }
        }
    }

    @Override
    public void receive2101(String devsn, String json) {
        MessageBase<U_Message2101> m2101 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message2101>>() {
        });

        if (m2101 != null) {
            if (m2101.getStatus().equals("3")) {
                if (StringUtils.isNoneBlank(m2101.getDeviceid()) && StringUtils.isNoneBlank(m2101.getStatus())) {
                    stlDevSyncMapper.updateNewestDevState(m2101.getDeviceid(), m2101.getStatus());
                }
            }
        }
    }

    @Override
    public synchronized void receive3001(String devsn, String json) {

        MessageBase<U_Message3001> m3001 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message3001>>() {
        });

        if (m3001 != null) {
            //查询设备状态是否存在
            DevStatus devStatus = devStatusMapper.selectByPrimaryKey(devsn);
            if (devStatus != null) {
                devStatus.setDevSn(devsn);
                devStatus.setIp(m3001.getContent().getIp());
                devStatus.setMac(m3001.getContent().getMac());
                devStatus.setTemperature(m3001.getContent().getTemperature());
                devStatus.setTemperaturemax(m3001.getContent().getTemperaturemax());
                devStatus.setTemperaturemin(m3001.getContent().getTemperaturemin());
                devStatus.setHumidity(m3001.getContent().getHumidity());
                devStatus.setHumiditymax(m3001.getContent().getHumiditymax());
                devStatus.setHumiditymin(m3001.getContent().getHumiditymin());
                devStatus.setVoltage(m3001.getContent().getVoltage());
                devStatus.setSoftwareversion(m3001.getContent().getSoftwareversion());
                devStatus.setDiskspacefree(m3001.getContent().getDiskspacefree());
                devStatus.setDiskspacetotal(m3001.getContent().getDiskspacetotal());
                devStatus.setAdfilecount(m3001.getContent().getAdfilecount());
                devStatus.setAdfilesize(m3001.getContent().getAdfilesize());
                devStatus.setLogfilecount(m3001.getContent().getLogfilecount());
                devStatus.setLogfilesize(m3001.getContent().getLogfilesize());

                if (m3001.getContent().getDoor() != null) {
                    devStatus.setDoorstatus(m3001.getContent().getDoor().getStatus());
                    devStatus.setDoortime(DateUtil.string2Date(m3001.getContent().getDoor().getTime(), "yyyy-MM-dd hh:mm:ss"));
                }

                devStatusMapper.updateByPrimaryKeySelective(devStatus);
            } else {
                devStatus = new DevStatus();
                devStatus.setGuid(devsn);
                devStatus.setDevSn(devsn);
                devStatus.setIp(m3001.getContent().getIp());
                devStatus.setMac(m3001.getContent().getMac());
                devStatus.setTemperature(m3001.getContent().getTemperature());
                devStatus.setHumidity(m3001.getContent().getHumidity());
                devStatus.setVoltage(m3001.getContent().getVoltage());
                devStatus.setSoftwareversion(m3001.getContent().getSoftwareversion());
                devStatus.setDiskspacefree(m3001.getContent().getDiskspacefree());
                devStatus.setDiskspacetotal(m3001.getContent().getDiskspacetotal());
                devStatus.setAdfilecount(m3001.getContent().getAdfilecount());
                devStatus.setAdfilesize(m3001.getContent().getAdfilesize());
                devStatus.setLogfilecount(m3001.getContent().getLogfilecount());
                devStatus.setLogfilesize(m3001.getContent().getLogfilesize());
                devStatus.setIsreg("1");
                if (m3001.getContent().getDoor() != null) {
                    devStatus.setDoorstatus(m3001.getContent().getDoor().getStatus());
                    devStatus.setDoortime(DateUtil.string2Date(m3001.getContent().getDoor().getTime(), "yyyy-MM-dd hh:mm:ss"));
                }

                devStatusMapper.insertSelective(devStatus);
            }

            //继电器
            if (m3001.getContent().getChannels() != null && m3001.getContent().getChannels().size() > 0) {

                //删除现有继电器
                devChannelNoMapper.deleteChannelByDevsn(devsn);

                //重新插入新的继电器
                for (U_Message3001_Channel channel : m3001.getContent().getChannels()) {
                    DevChannelNo devChannelNo = new DevChannelNo();
                    devChannelNo.setGuid(UUID.randomUUID().toString());
                    devChannelNo.setDevSn(devsn);
                    devChannelNo.setChannelno(channel.getChannelno());
                    devChannelNo.setStatus(channel.getStatus());
                    devChannelNo.setStart(channel.getStart());
                    devChannelNo.setEnd(channel.getEnd());
                    devChannelNo.setChannelname(channel.getChannelname());
                    devChannelNoMapper.insert(devChannelNo);
                }
            }
        }
    }

    @Override
    public void receive3002(String devsn, String json) {
        // 记录设备告警信息
        MessageBase<U_Message3002> m3002 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message3002>>() {
        });

        if (m3002 != null) {
            if (m3002.getContent() != null) {
                U_Message3002 message3002 = m3002.getContent();
                DevAlertInfo devAlertInfo = new DevAlertInfo();
                devAlertInfo.setGuid(UUID.randomUUID().toString());
                devAlertInfo.setType(message3002.getType());
                devAlertInfo.setInfo(message3002.getInfo());
                devAlertInfo.setIscancel("0");
                devAlertInfo.setDevid(devsn);
                devAlertInfo.setCreatetime(new Date());
                devAlertInfo.setSendtime(new Date());
                devAlertInfoMapper.insert(devAlertInfo);

                try {
                    iRepairService.alertReport(devsn, message3002.getType(), message3002.getInfo());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

    }

    @Override
    public void receive3003(String devsn, String json) {
        MessageBase<U_Message3003> m3003 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message3003>>() {
        });

        if (m3003 != null && m3003.getStatus().equals("200")) {

            //查询设备状态是否存在
            DevStatus devStatus = devStatusMapper.selectByPrimaryKey(devsn);
            if (devStatus != null) {
                devStatus.setHeartbeatpretime(devStatus.getHeartbeatlasttime());
                devStatus.setHeartbeatlasttime(new Date());
                devStatusMapper.updateByPrimaryKeySelective(devStatus);
            } else {
                devStatus = new DevStatus();
                devStatus.setGuid(devsn);
                devStatus.setDevSn(devsn);
                devStatus.setHeartbeatlasttime(new Date());
                devStatus.setIsreg("1");
                devStatusMapper.insertSelective(devStatus);
            }
        }
    }

    @Override
    public void receive4003(String devsn, String json) {
        MessageBase<U_Message4003> m4003 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message4003>>() {
        });

        List<MqGridSelectedDevModel> mqGridSelectedDevModels = new ArrayList<>();
        MqGridSelectedDevModel dev = new MqGridSelectedDevModel();
        dev.setEquipmentno(devsn);
        mqGridSelectedDevModels.add(dev);
        send4003(DateUtil.date2String(new Date(), "HH:mm:ss"), mqGridSelectedDevModels);

    }

    @Override
    public void receive4007(String devsn, String json) {
        MessageBase<U_Message4007> m4007 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message4007>>() {
        });

        // 获取当前设备关联的升级包
        List<DevVersionRecord> devVersionRecords = devVersionRecordMapper.findAllDevVersionRecord();
        DevVersionMap devVersionMap = devVersionMapMapper.selectByDevsn(devsn);
        DevVersionRecord record = null;
        if (devVersionMap.getIsupdatefromserver().equals("1")) {
            // 获取最新升级包
            record = devVersionRecordMapper.selectByNewestVersion();
        } else {
            // 获取当前设备关联的升级包
            record = devVersionRecordMapper.selectByPrimaryKey(devVersionMap.getVersionid());
        }

        MqPushUpdatePackageModel model = new MqPushUpdatePackageModel();
        model.setVersion(record.getVersion());
        model.setMqSelectedDevModels(new ArrayList<>());
        MqSelectedDevModel dev = new MqSelectedDevModel();
        dev.setDevsn(devsn);
        model.getMqSelectedDevModels().add(dev);
        model.setRequesttype("request");
        send4007(model);
    }

    @Override
    public void receive4008(String devsn, String json) {
        MessageBase<U_Message4008> m4008 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message4008>>() {
        });

        if (m4008 != null) {
            devStatusMapper.updateDevStatusVersion(devsn, m4008.getContent().getVersion());
            upDevUpdateReplayProgressMapper.updateReplayTime(devsn, m4008.getContent().getVersion(), DateUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        }
    }

    @Override
    public void receive4009(String devsn, String json) throws Exception {
        MessageBase<U_Message4009> m4009 = JSON.parseObject(json, new TypeReference<MessageBase<U_Message4009>>() {
        });

        if (m4009 != null) {
            devImgMapper.deleteByDevsn(devsn);
            DevImg devImg = new DevImg();
            devImg.setGuid(UUID.randomUUID().toString());
            devImg.setDevId(devsn);
            devImg.setImgTime(new Date());
            devImg.setBase64(URLDecoder.decode(m4009.getContent().getBase64(), "UTF-8"));
            devImg.setFiletype("jpg");
            devImgMapper.insert(devImg);


        }
    }

    private void PushWebPageSocket(String content) {
        try {
            MyWebSocket.sendWebClientInfo(content);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
    }

    /**
     * 首页动态实时数据采集写入（上行）
     *
     * @param index  指令代码
     * @param name   指令名称
     * @param devsn  设备编码
     * @param length 字符串长度
     */
    private void webSocketMapInfo(int index, String name, String devsn, int length) {
//        CmdRecord cmdRecord = new CmdRecord();
//        cmdRecord.setCmdtime(new Date());
//        cmdRecord.setCmdcode(String.valueOf(index));
//        cmdRecord.setCmdname(name);
//        cmdRecord.setCmdtype("request");
//        cmdRecord.setEquipmentno(devsn);
//        cmdRecord.setCmdbytelength(length);
//
//        if (websocketMap.isEmpty()) {
//            timeMillions = Calendar.getInstance().getTimeInMillis();
//            websocketMap.put(UUID.randomUUID().toString(), cmdRecord);
//
//        } else {
//            // 超过10分钟则将数据写入DB
//            if (Calendar.getInstance().getTimeInMillis() - timeMillions > 600000) {
//                List<CmdRecord> list = new ArrayList<CmdRecord>();
//
//                // 创建时间
//                Date date = new Date();
//
//                // 遍历map，生成对象list
//                for (String key : websocketMap.keySet()) {
//                    CmdRecord cr = websocketMap.get(key);
//                    cr.setGuid(key);
//                    cr.setCreatetime(date);
//                    list.add(cr);
//                }
//
//                // cmdRecord 插入操作
//                if (list.size() > 0) {
//                    cmdRecordMapper.insertSelectiveList(list);
//                }
//
//                websocketMap.clear();
//                timeMillions = Calendar.getInstance().getTimeInMillis();
//                websocketMap.put(UUID.randomUUID().toString(), cmdRecord);
//            } else {
//                // 不超过10分钟，写入map
//                websocketMap.put(UUID.randomUUID().toString(), cmdRecord);
//            }
//        }
    }
    // endregion

}